package com.neutech.service.impl;

import com.neutech.service.MinioService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class MinioServiceImpl implements MinioService {
    @Value("${minio.endpoint}")
    String endpoint;
    @Value("${minio.username}")
    String username;
    @Value("${minio.password}")
    String password;
    private MinioClient createClient() {
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(username, password)
                .build();
    }
    private String getName(String oldName) {
        StringBuilder name = new StringBuilder();
        name.append(
                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")))
                .append(".")
                .append(FilenameUtils.getExtension(oldName));
        return name.toString();

    }
    @Override
    public String upload(MultipartFile file) throws Exception {
        MinioClient client = createClient();
        String bucketName = "audio";
        String fileName = getName(file.getOriginalFilename());
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        client.close();
        return bucketName + "/" + fileName;
    }
}
